package parsers.reservation;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import dao.Linker;

import parsers.CommonMethods;

import model.Time;
import model.Warning;
import model.reservation.teacher.Day;
import model.reservation.teacher.Reservation;
import model.reservation.teacher.Subject;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Segment;
import net.htmlparser.jericho.Source;

public class ReservationTParser
{	
	private Reservation reservation;
	
	public ReservationTParser(Reservation reservation) 
	{
		this.reservation = reservation;
	}
	
	public Reservation parse() throws IOException
	{	
		Source source = new Source(new URL(reservation.getLink()));
		List<Element> elements = source.getAllElements(HTMLElementName.TR);
		
		Day day = null;
		
		for (Element element : elements)
		{
			List<Element> e = element.getAllElements("b");
			
			for (Element element2 : e)
			{
				if(CommonMethods.checkDay(element2.getContent().toString()))
				{
					day = reservation.createDay(element2.getContent().toString());
				}
			}
			
			if(day != null)
			{
				e = element.getAllElements("tr");
				for (Element element2 : e)
				{
					Segment s = element2.getContent();
					List<Element> el = s.getAllElements("td");
					
					if(el.size() > 1)
					{
						Warning warning = new Warning(CommonMethods.parseElement(el.get(6)));
						Linker.warningRAWList.add(warning);
						Subject subject = day.createSubject(new Time(CommonMethods.checkSpace(el.get(0).getContent().toString()), CommonMethods.checkSpace(el.get(1).getContent().toString())), el.get(2).getContent().toString(), el.get(3).getContent().toString(), warning);
						
						CommonMethods.parseGroups(el.get(4), subject);
						CommonMethods.parseLectureRooms(el.get(5), subject);
					}
				}
			}
		}
		
		return reservation;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		LectureRoom lr = new LectureRoom("113 A-29", "30", "sala ćwiczeniowa", "Wydział Matematyki, Informatyki i Ekonometrii");
		lr.setLink("file:/D:/test9.html");
		LectureRoomParser lrp = new LectureRoomParser(lr);
		LectureRoom l = lrp.parse(true);
		System.out.println(lr);
	}*/
}
